package cn.longg.service.impl;

import cn.longg.entity.User;
import cn.longg.mapper.UserMapper;
import cn.longg.service.IUserService;
import cn.longg.utils.CodeUtil;
import cn.longg.utils.JedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    private Jedis jedis = JedisUtil.getJedis();
    @Override
    public int checkRegister(User user) {
        int result = 0;
        Map<String, String> checkRegister = jedis.hgetAll("checkRegister");
        if(null == checkRegister || 0 == checkRegister.size()){
            List<User> users = this.selectAll();
            checkRegister = new HashMap<>();
            for (User user1 : users) {
                if(null == user1.getUsername()){
                    user1.setUsername("");
                }
                if(null == user1.getEmail()){
                    user1.setEmail("");
                }
                jedis.hset("checkRegister",user1.getUsername(),user1.getEmail());
                checkRegister.put(user1.getUsername(),user1.getEmail());
            }
        }
        Set<Map.Entry<String, String>> entries = checkRegister.entrySet();
        if(null != user.getUsername() && !"".equals(user.getUsername())){
            for (Map.Entry<String, String> entry : entries) {
                if(user.getUsername().equals(entry.getKey())){
                    result += 1;
                    break;
                }
            }
        }
        if(null != user.getEmail() && !"".equals(user.getEmail())){
            for (Map.Entry<String, String> entry : entries) {
                if(user.getEmail().equals(entry.getValue())){
                    result += 2;
                    break;
                }
            }
        }

        return result;
    }

    @Override
    public int doRegister(User user) {
        int i = this.insertSelective(user);
        jedis.hset("checkRegister",user.getUsername(),user.getEmail());
        return i;
    }

    @Override
    public void remember(String key, String value) {
        //一个星期的记住我
        jedis.set(key,value,"NX","EX",60*60*24*7);

    }

    @Override
    public String getRemember(String key) {
        return jedis.get(key);
    }

    @Override
    public void delRemember(String key) {
        jedis.del(key);
    }

    @Override
    public boolean checkEmail(String email) {
        Map<String, String> checkRegister = jedis.hgetAll("checkRegister");
        Set<Map.Entry<String, String>> entries = checkRegister.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if(email.equals(entry.getValue())){
                return true;
            }
        }
        return false;
    }

    @Override
    public String sendEmailCode(String email) {
        return CodeUtil.sendCode(4,email);
    }

    @Override
    public String getEmailCode(String key) {
        return jedis.get(key);
    }

    @Override
    public void setEmailCode(String key,String code) {
        jedis.set(key,code,"NX","EX",60);
    }

    @Override
    public int getFansNum(Integer id) {
        return userMapper.getFansNum(id);
    }

    @Override
    public PageInfo selectByPage(String name, int page, int pageSize) {
        PageHelper.startPage(page,pageSize);
        List<User> userList = userMapper.selectAllByName(name);
        for (User user : userList) {
            user.setFansNum(getFansNum(user.getId()));
        }
        return new PageInfo(userList);
    }

    @Override
    public void lookIncr(User user) {
        synchronized (this){
            userMapper.lookIncr(user.getId());
        }
    }

    @Override
    public List<Integer> selectFocusUser(User checkUser) {
        List<Integer> userList = userMapper.selectFocusUser(checkUser.getId());
        return userList;
    }

    @Override
    public boolean focus(User user,User loginUser) {
        int i = userMapper.focus(user.getId(),loginUser.getId());
        return 0 < i;
    }

    @Override
    public boolean unfocus(User user, User loginUser) {
        int i = userMapper.unfocus(user.getId(),loginUser.getId());
        return 0 < i;
    }

    @Override
    public PageInfo selectFocusUserByPage(int page, int pageSize,User loginUser) {
        PageHelper.startPage(page,pageSize);
        List<User> userList = userMapper.selectFocusUserList(loginUser.getId());
        return new PageInfo(userList);
    }

    @Override
    public List<User> getUserByDeptId(Integer deptId) {
        List<User> userList = userMapper.selectByDeptId(deptId);
        return userList;
    }

    @Override
    public String upload(MultipartFile file,User loginUser) {
        String picUrl = null;
        try {
            InputStream is = file.getInputStream();
            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + suffix;
            FileOutputStream fos = new FileOutputStream(new File("D:\\idea\\upload\\" + fileName));
            int len = 0;
            byte[] bytes = new byte[1024];
            while(-1 != (len = is.read(bytes))){
                fos.write(bytes,0,len);
            }
            fos.close();
            is.close();
            picUrl = "upload/" + fileName;
            loginUser.setPic(picUrl);
            updateByPrimaryKey(loginUser);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return picUrl;
    }


}
